import { defineComponent, reactive } from 'vue';
import { AppComponentBase } from '/@/shared/component-base';
import { AppConsts } from '/@/abpPro/AppConsts';
import { impersonationService } from '/@/shared/auth';
import {
  EntityDtoOfInt64,
  UserExtensionServiceProxy,
  UserListDto,
} from '/@/shared/service-proxies/service-proxies';
import {
  CheckCircleTwoTone,
  CloseCircleTwoTone,
  PlusOutlined,
  EditOutlined,
  DeleteOutlined,
  LoginOutlined,
  UnlockOutlined,
  CodepenOutlined,
  FilterOutlined,
  DownOutlined,
} from '@ant-design/icons-vue';
import { RoleCombox, PermissionCombox } from '/@/app/admin-shared';
import CreateOrEditUserCompent from './create-or-edit-user/create-or-edit-user.vue';
import EditUserPermissionsCompent from './edit-user-permission/edit-user-permission.vue';
import { UserServiceProxy, GetUsersInput } from '/@/shared/service-proxies';
import { EVENT_BTN_ENUM } from '/@/shared/components/g-dynamic-table/enums/event-btn-enum';
import { fileDownloadService } from '/@/shared';
export default defineComponent({
  name: 'UsersNew',
  components: {
    PermissionCombox,
    RoleCombox,
    CheckCircleTwoTone,
    CloseCircleTwoTone,
    PlusOutlined,
    EditOutlined,
    DeleteOutlined,
    LoginOutlined,
    UnlockOutlined,
    CodepenOutlined,
    FilterOutlined,
    DownOutlined,
    CreateOrEditUserCompent,
    EditUserPermissionsCompent,
  },
  mixins: [AppComponentBase],
  data() {
    return {
      /** 是否显示高级过滤 */
      advancedFiltersVisible: false,
      /** 选中的权限过滤 */
      selectedPermission: [] as any,
      /** 选中的角色Ids过滤 */
      role: [] as number[],
      /** 是否已验证邮箱过滤 */
      isEmailConfirmed: undefined,
      /** 是否激活过滤 */
      isActive: undefined,
      /** 用户api */
      userSer: new UserServiceProxy(this.$apiUrl, this.$api),
      _userExtensionService: new UserExtensionServiceProxy(this.$apiUrl, this.$api),
      dataList: [] as UserListDto[],

      item: {} as UserListDto,
      /** 选中 */
      selectItems: [] as any[],
      fileDownloadSer: fileDownloadService,
    };
  },
  computed: {
    rolesEllipsis() {
      return (roles) => {
        return roles
          .map((item) => {
            return item.roleName;
          })
          .join(', ');
      };
    },
    showActionBtn() {
      /**
       * item 按钮json配置项
       * column table 当前列配置
       * record 当前行数据
       */
      return (item, column, record) => {
        switch (item.name) {
          case EVENT_BTN_ENUM.DELETE:
            return !this.isAdmin(record) && !this.isCurrentUser(record);
          case EVENT_BTN_ENUM.EDIT:
            return !this.isSuperAdmin(record);
          case EVENT_BTN_ENUM.LOGIN_AS_THIS_USER:
            return !this.isAdmin(record) && !this.isCurrentUser(record);
          case EVENT_BTN_ENUM.UNLOCK:
            return !this.isAdmin(record) && this.enabledUnlock();
          default:
            return true;
        }
      };
    },
    /**
     * 格式化导出值
     */
    formartColumn() {
      return (field, value) => {
        if (field == 'roles') {
          return this.rolesEllipsis(value);
        }
        return value;
      };
    },
  },
  mounted() {
    (this.$refs.table as any).setRowSelection('getCheckboxProps', (record) => {
      return {
        disabled: this.isAdmin(record) || this.isCurrentUser(record),
      };
    });
  },
  methods: {
    /**
     * table默认配置 （是否禁用）
     */
    getCheckboxProps(item: UserListDto) {
      return {
        disabled: this.isAdmin(item) || this.isCurrentUser(item),
      };
    },
    /**
     * 添加用户  修改用户
     */
    createOrEdit(item?: UserListDto) {
      this.selectItems = [];
      // this.item = !!item ? item : ({} as UserListDto);
      if (!!item && item.id) {
        this.selectItems = [item.id];
      }
      this.modalHelper
        .create(CreateOrEditUserCompent, {
          pageDataList: this.selectItems,
          userName: this.item.userName,
        })
        .subscribe((res) => {
          if (res) {
            (this.$refs.table as any).reloadGoFirstPage();
          }
        });
    },
    /**
     * 批量删除
     */
    batchDelete() {
      const table = this.$refs.table as any;
      if (table.getSelectRowKeys().length <= 0) {
        this.notify.warn(this.l('PleaseSelectAtLeastOneItem'));
        return;
      }
      this.message.confirm(
        this.l('ConfirmDeleteXItemsWarningMessage', table.getSelectRowKeys().length),
        '',
        (res: any) => {
          if (res) {
            const ids = [...table.getSelectRowKeys()];
            (this.$refs.table as any).setLoading(true);
            this.userSer
              .batchDelete(ids)
              .finally(() => {
                (this.$refs.table as any).setLoading(false);
              })
              .then(() => {
                (this.$refs.table as any).reloadGoFirstPage();
                this.notify.success(this.l('SuccessfullyDeleted'));
              });
          }
        },
      );
    },
    /**
     * 单个删除
     */
    deleteItem(item: UserListDto) {
      if ((item as any).isStatic) {
        this.notify.warn(
          this.l('XUserCannotBeDeleted', AppConsts.userManagement.defaultAdminUserName),
        );
        return;
      }
      (this.$refs.table as any).setLoading(true);
      this.userSer
        .delete(item.id)
        .finally(() => {
          (this.$refs.table as any).setLoading(false);
        })
        .then(() => {
          (this.$refs.table as any).reloadGoFirstPage();
          this.notify.success(this.l('SuccessfullyDeleted'));
        });
    },
    /**
     * 批量编辑
     */
    bulkEdit() {
      this.selectItems = [];
      let arr = (this.$refs.table as any).getSelectRowKeys();
      if (arr.length < 1) {
        return this.notify.warn(this.l('PleaseSelectAtLeastOneItem'));
      }
      this.selectItems = arr;
      this.modalHelper
        .create(CreateOrEditUserCompent, {
          pageDataList: this.selectItems,
          userName: this.item.userName,
        })
        .subscribe((res) => {
          if (res) {
            (this.$refs.table as any).reloadGoFirstPage();
          }
        });
    },
    /** 筛选权限发生变更 */
    selectedPermissionChange(permissions: string[]) {
      this.selectedPermission = permissions;
      // this.getSearchData();
    },
    /** 角色过滤选择 */
    selectedRoleChange(roles: number[]) {
      this.role = roles;
      // this.getSearchData();
    },
    /** 是否是当前用户 */
    isCurrentUser(item: UserListDto) {
      return item.id === this.abpSession.userId;
    },
    /** 是否是管理员 */
    isAdmin(item: UserListDto) {
      return (
        item.userName === AppConsts.userManagement.defaultAdminUserName ||
        item.userName === AppConsts.superUserManagement.defaultAdminUserName
      );
    },
    /** 是否为系统默认不可删除的SuperAdmin用户 */
    isSuperAdmin(item: UserListDto): boolean {
      return item.userName === AppConsts.superUserManagement.defaultAdminUserName;
    },
    /** 是否显示解锁按钮 */
    enabledUnlock() {
      return (
        this.isGranted('Pages.Administration.Users.Edit') &&
        this.setting.getBoolean('Abp.Zero.UserManagement.UserLockOut.IsEnabled')
      );
    },
    /** 使用此账户登录 */
    tenantImpersonateLogin(item: UserListDto) {
      impersonationService.impersonate(item.id, this.abpSession.tenantId);
    },
    /** 编辑用户权限 */
    editUserPermissions(item: UserListDto) {
      this.modalHelper
        .create(EditUserPermissionsCompent, { pageDataList: item?.id, userName: item.userName })
        .subscribe((res) => {
          if (res) {
            (this.$refs.table as any).reloadGoFirstPage();
          }
        });
    },
    /** 解锁 */
    unlockTenantAdminUser(item: UserListDto) {
      (this.$refs.table as any).setLoading(true);
      const input: EntityDtoOfInt64 = new EntityDtoOfInt64();
      input.init(item);
      this.userSer
        .unlock(input)
        .finally(() => {
          (this.$refs.table as any).setLoading(false);
        })
        .then(() => {
          (this.$refs.table as any).reload();
          this.notify.success(this.l('UserUnblocked'));
        });
    },
    /**
     * 获取数据
     */
    fetchDataList(otherQuery) {
      const { maxResultCount, skipCount, sorting, UserName, Permissions, Role, CreationTime } = (
        this.$refs.table as any
      ).getSearchProps();
      const input = new GetUsersInput();
      input.permission = Permissions;
      input.role = Role;
      input.isEmailConfirmed = this.isEmailConfirmed;
      input.isActive = this.isActive;
      input.startTime = !CreationTime ? undefined : CreationTime[0];
      input.endTime = !CreationTime ? undefined : CreationTime[1];
      input.filterText = UserName;
      input.sorting = sorting;
      input.maxResultCount = !!otherQuery ? otherQuery.maxResultCount : maxResultCount;
      input.skipCount = !!otherQuery ? otherQuery.skipCount : skipCount;
      return new Promise((resolve, reject) => {
        this.userSer
          .getPaged(input)
          .finally(() => {
            // finishedCallback!();
          })
          .then((res) => {
            resolve(res);
            // this.showPaging(res);
          })
          .catch((error) => {
            reject(error);
          });
      });
    },
    /**用户数据导入 */
    importUserExcels(idx: string, name: string) {
      this._userExtensionService.importUserExcel(idx).then((item) => {
        const Refs = (this.$refs as any).table.getRef(name);
        if (Refs == undefined) {
          this.notify.error('Refs is undefined');

          return;
        } else {
          (this.$refs as any).table.getRef(name).initImportReturn(item);
          (this.$refs as any).table.reloadGoFirstPage();
        }
      });
    },
    /*下载模板*/
    downloadTemplate() {
      this._userExtensionService.userExtensionDownloadTemplate().then((result) => {
        this.fileDownloadSer.downloadTempFile(result);
      });
    },
    /**
     * 按钮回调事件
     */
    handleActionClick(event: string, item?: any) {
      console.log(event);
      switch (event) {
        case EVENT_BTN_ENUM.CREATE:
          this.createOrEdit();
          break;
        case EVENT_BTN_ENUM.BULK_EDIT:
          this.bulkEdit();
          break;
        case EVENT_BTN_ENUM.DELETE:
          this.deleteItem(item);
          break;
        case EVENT_BTN_ENUM.BULK_DELETE:
          this.batchDelete();
          break;
        case EVENT_BTN_ENUM.EDIT:
          this.createOrEdit(reactive(item));
          break;
        case EVENT_BTN_ENUM.LOGIN_AS_THIS_USER:
          this.tenantImpersonateLogin(item);
          break;
        case EVENT_BTN_ENUM.PERMISSIONS:
          this.editUserPermissions(item);
          break;
        case EVENT_BTN_ENUM.UNLOCK:
          this.unlockTenantAdminUser(item);
          break;
        case EVENT_BTN_ENUM.IMPORT:
          this.importUserExcels(item, event);
          break;
        case EVENT_BTN_ENUM.DOWNLOAD_EXCEL_TEMPLATE:
          this.downloadTemplate();
          break;
        default:
          break;
      }
    },
  },
});
